<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 只有一种情况必须用递归 你不确定有几层 无限级菜单
        // 不确定有几层 只能用递归
        // parent id 父级id 
        var depts = [
            { id: 1, pid: "", name: "aaa" },
            { id: 2, pid: 1, name: "bbb" },
            { id: 3, pid: 1, name: "ccc" },
            { id: 5, pid: "", name: "eee" },
            { id: 6, pid: 2, name: "fff" },
        ];
        const arr1 = []
        // 谁都可以写出来 也看得懂
        depts.forEach((item1) => {
            if (item1.pid === '') {
                arr1.push(item1)
                const arr2 = []
                depts.forEach(item2 => {
                    if (item2.pid === item1.id) {
                        arr2.push(item2)
                        const arr3 = []
                        depts.forEach(item3 => {
                            if (item3.pid === item2.id) {
                                arr3.push(item3)
                            }
                        })
                        if (arr3.length > 0) {
                            item2.children = arr3
                        }
                    }
                })
                if (arr2.length > 0) {
                    item1.children = arr2
                }
            }
        })
        console.log(arr1);
    </script>
</body>

</html>